/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package golftourcalculator;

import golftourcalculator.dialogs.FXMLAddTournamentDialogController;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.controlsfx.control.action.Action;
import org.controlsfx.dialog.Dialog;
import org.controlsfx.dialog.DialogStyle;
import org.controlsfx.dialog.Dialogs;

/**
 *
 * @author Martin
 */
public class FXMLDocumentController implements Initializable {

    @FXML
    private MenuItem newTourMenuItem;

    @FXML
    private MenuItem openTourMenuItem;

    @FXML
    private MenuItem closeTourMenuItem;

    @FXML
    private MenuItem addTournamentMenuItem;

    @FXML
    private MenuItem deleteTournamentMenuItem;

    @FXML
    private MenuItem editTournamentMenuItem;

    @FXML
    private MenuItem addCategoryMenuItem;

    @FXML
    private MenuItem deleteCategoryMenuItem;

    @FXML
    private MenuItem editCategoryMenuItem;

    @FXML
    private MenuItem aboutMenuItem;

    @FXML
    private ComboBox categoryComboBox;

    @FXML
    private ComboBox<Tournament> tournamentComboBox;

    @FXML
    private TableView tableView;

    private Stage stage;

    @FXML
    private void newTourHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void openTourHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void closeTourHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void addTournamentHandleAction(ActionEvent event) {
        try {
            // Load the fxml file and create a new stage for the popup
            FXMLLoader loader = new FXMLLoader(GolfTourCalculator.class.getResource("dialogs/FXMLAddTournamentDialog.fxml"));
            AnchorPane page = (AnchorPane) loader.load();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("Add Tournament");
            dialogStage.initModality(Modality.WINDOW_MODAL);
            Scene scene = new Scene(page);
            dialogStage.setScene(scene);

            // Get the controller
            FXMLAddTournamentDialogController controller = loader.getController();
            controller.setDialogStage(dialogStage);

            // Show the dialog and wait until the user closes it
            dialogStage.showAndWait();

            if (controller.getCommit()) {

                String bruttoLink = controller.getBrutto();
                String nettoLink = controller.getNetto();

                String[] bruttoLinks = bruttoLink.split(";");
                String[] nettoLinks = nettoLink.split(";");

                HTMLParser parser = new HTMLParser(bruttoLinks, nettoLinks);

                parser.parse();

                ObservableList<TournamentResult> list = parser.result();

                this.prepareTableForTournament();

                Tournament newTournament = new Tournament(controller.getTournamentName(), list);

                this.tableView.setItems(newTournament.getList());

                this.tournamentComboBox.getItems().add(newTournament);
                this.tournamentComboBox.getSelectionModel().select(newTournament);
            }
        } catch (IOException ex) {

            Dialogs.create()
                    .owner(stage)
                    .style(DialogStyle.NATIVE)
                    .title("Error")
                    .masthead("Nastal problém při načítání webu.")
                    .message("Překontroluje si vloženou adresu.")
                    .showError();
        } catch (HTMLParser.HTMLParserException ex) {

            Dialogs.create()
                    .owner(stage)
                    .style(DialogStyle.NATIVE)
                    .title("Error")
                    .masthead("Nastal problém při prohledávání webu.")
                    .message(ex.getMessage())
                    .showError();
        }
    }

    @FXML
    private void deleteTournamentHandleAction(ActionEvent event) {

        if (this.tournamentComboBox.getValue() != null) {
            Action response = Dialogs.create()
                    .owner(stage)
                    .style(DialogStyle.NATIVE)
                    .title("Potvrzení")
                    .masthead("Mažete turnaj:" + this.tournamentComboBox.getValue().getTournamentName())
                    .message("Chcete ho opravdu smazat?")
                    .actions(Dialog.Actions.YES, Dialog.Actions.NO)
                    .showConfirm();

            if (response == Dialog.Actions.YES) {
                Tournament current = this.tournamentComboBox.getValue();
                int index = this.tournamentComboBox.getItems().indexOf(current);

                // TODO pro pripad jednoho turnaje
                Tournament next;
                if (1 < this.tournamentComboBox.getItems().size()) {

                    if ((index + 1) < this.tournamentComboBox.getItems().size()) {
                        next = this.tournamentComboBox.getItems().get(index + 1);
                    } else {
                        next = this.tournamentComboBox.getItems().get(0);
                    }

                    this.tournamentComboBox.setValue(next);

                    this.tournamentComboBox.getItems().remove(current);
                } else {

                    this.tournamentComboBox.getSelectionModel().clearSelection();
                    this.tournamentComboBox.getItems().remove(current);
                }
            }
        } else {
            
            Dialogs.create()
                    .owner(stage)
                    .style(DialogStyle.NATIVE)
                    .title("Chyba")
                    .message("Není vybrán turnaj ke smazání nebo žádný neexistuje.")
                    .showWarning();
        }
    }

    @FXML
    private void editTournamentHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void addCategoryHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void deleteCategoryHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void editCategoryHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void aboutMenuHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void categoryChoiceHandleAction(ActionEvent event) {
        // TODO
    }

    @FXML
    private void tournamentChoiceHandleAction(ActionEvent event) {

        ObservableList<TournamentResult> list;

        if ((0 < this.tournamentComboBox.getItems().size()) && (this.tournamentComboBox.getValue() != null)) {

            list = this.tournamentComboBox.getValue().getList();
            this.prepareTableForTournament();
        } else {

            list = null;
        }

        this.tableView.setItems(list);
    }

    private void prepareTableForCategory() {
        // TODO
    }

    private void prepareTableForTournament() {
        TableColumn<TournamentResult, String> rankCol = new TableColumn<>("Pořadí");
        rankCol.setCellValueFactory(new PropertyValueFactory("rank"));
        TableColumn<TournamentResult, String> nameCol = new TableColumn<>("Jméno");
        nameCol.setCellValueFactory(new PropertyValueFactory("playerName"));
        TableColumn<TournamentResult, String> clubCol = new TableColumn<>("Klub");
        clubCol.setCellValueFactory(new PropertyValueFactory("clubAbbreviation"));
        TableColumn<TournamentResult, String> idCol = new TableColumn<>("Číslo reg.");
        idCol.setCellValueFactory(new PropertyValueFactory("cardId"));
        TableColumn<TournamentResult, String> bruttoCol = new TableColumn<>("Brutto");
        bruttoCol.setCellValueFactory(new PropertyValueFactory("bruttoResult"));
        TableColumn<TournamentResult, String> nettoCol = new TableColumn<>("Netto");
        nettoCol.setCellValueFactory(new PropertyValueFactory("nettoResult"));
        TableColumn<TournamentResult, String> celkemCol = new TableColumn<>("Celkem");
        celkemCol.setCellValueFactory(new PropertyValueFactory("result"));

        this.tableView.getColumns().setAll(rankCol, nameCol, clubCol, idCol, bruttoCol, nettoCol, celkemCol);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        this.tournamentComboBox.setCellFactory(new Callback<ListView<Tournament>, ListCell<Tournament>>() {

            @Override
            public ListCell<Tournament> call(ListView<Tournament> p) {

                final ListCell<Tournament> cell = new ListCell<Tournament>() {

                    @Override
                    protected void updateItem(Tournament t, boolean bln) {
                        super.updateItem(t, bln);

                        if (t != null) {
                            setText(t.getTournamentName());
                        } else {
                            setText(null);
                        }
                    }
                };

                return cell;
            }
        });
    }

    /**
     * @param stage the stage to set
     */
    public void setStage(Stage stage) {
        this.stage = stage;
    }

}
